// miniprogram/pages/user-center/user-center.js
const app = getApp();

Page({
  data: {
    userInfo: null,
    isLoggedIn: false,
    isAdmin: false, // 用于控制管理后台入口
    orderStats: {
      pending: 0,
      completed: 0
    },
    loading: {
      stats: false,
      profile: false
    },
    refreshing: false,
    // 仅保留已实现的核心功能项
    menuItems: [
      { icon: 'icon-history', label: '打印历史', url: '/pages/history/history', type: 'link' }
    ]
  },

  onShow() {
    this.checkLoginStatus();

    // --- ***修改：同时检查全局(OPENID)和本地存储(密码)的管理员状态*** ---
    const hasOpenIDAccess = app.globalData.isAdmin || false;
    const hasPasswordAccess = wx.getStorageSync('isAdmin') || false;
    this.setData({
      isAdmin: hasOpenIDAccess || hasPasswordAccess
    });
    // ---------------------------------
    
    if (this.data.isLoggedIn) {
      this.safeFetchStats();
    }
  },

  onPullDownRefresh() {
    this.setData({ refreshing: true });
    
    // --- ***修改：下拉刷新时也刷新两种管理员状态*** ---
    const hasOpenIDAccess = app.globalData.isAdmin || false;
    const hasPasswordAccess = wx.getStorageSync('isAdmin') || false;
    this.setData({
      isAdmin: hasOpenIDAccess || hasPasswordAccess
    });
    // ------------------------------------

    if (this.data.isLoggedIn) {
      this.safeFetchStats(() => {
        wx.stopPullDownRefresh();
        this.setData({ refreshing: false });
        wx.vibrateShort({ type: 'light' });
      });
    } else {
      wx.stopPullDownRefresh();
      this.setData({ refreshing: false });
    }
  },

  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userInfo,
      isLoggedIn: !!userInfo
    });
  },

  // 轻量封装，带loading的统计获取
  safeFetchStats(done) {
    if (this.data.loading.stats) return;
    this.setData({ 'loading.stats': true });
    this.getOrderStats()
      .catch(() => {})
      .finally(() => {
        this.setData({ 'loading.stats': false });
        typeof done === 'function' && done();
      });
  },

  // 获取订单统计数据
  getOrderStats() {
    const db = wx.cloud.database();
    const openid = wx.getStorageSync('userInfo')?.openid;
    if (!openid) return Promise.resolve();

    return Promise.all([
      db.collection('orders').where({ _openid: openid, printStatus: 'pending' }).count(),
      db.collection('orders').where({ _openid: openid, printStatus: 'completed' }).count()
    ]).then(([pendingRes, completedRes]) => {
      this.setData({
        'orderStats.pending': pendingRes.total,
        'orderStats.completed': completedRes.total
      });
    }).catch(err => {
      console.error('获取订单统计失败', err);
      wx.showToast({ title: '刷新失败', icon: 'none' });
      throw err;
    });
  },

  // 登录跳转
  handleLogin() {
    if (!this.data.isLoggedIn) {
      wx.navigateTo({ url: '/pages/login/login' });
    }
  },

  // 历史跳转（卡片/菜单均复用）
  gotoHistory() {
    const url = this.data.isLoggedIn ? '/pages/history/history' : '/pages/login/login';
    wx.navigateTo({ url });
  },

  // 菜单点击
  handleMenuTap(e) {
    const item = e.currentTarget.dataset.item;
    if (item.type === 'link') {
      if (item.url) {
        // 如果点击的是管理后台，但未登录，则跳转到管理员登录页
        if (item.url.startsWith('/admin/') && !this.data.isAdmin) {
            wx.navigateTo({ url: '/admin/login/login' });
            return;
        }

        if (!this.data.isLoggedIn && item.url.indexOf('/history/') !== -1) {
          wx.navigateTo({ url: '/pages/login/login' });
          return;
        }
        
        wx.navigateTo({ url: item.url });
      }
    }
    // contact 类型由 open-type="contact" 触发，无需处理
  },

  // 退出登录
  handleLogout() {
    wx.showModal({
      title: '确认退出',
      content: '退出后将无法查看订单统计，是否继续？',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          // --- ***修改：清除所有登录凭据*** ---
          wx.removeStorageSync('userInfo');
          wx.removeStorageSync('isAdmin'); // 清除密码登录凭据
          app.globalData.isAdmin = false; // 清除 OPENID 凭据
          // -------------------------------

          this.setData({
            userInfo: null,
            isLoggedIn: false,
            isAdmin: false, // 重置页面状态
            orderStats: { pending: 0, completed: 0 }
          });
          wx.showToast({ title: '已退出', icon: 'success' });
          wx.vibrateShort({ type: 'heavy' });
        }
      }
    });
  }
});